package com.coastline.fruit.manage.service.impl;

import com.coastline.fruit.common.constants.CommonConstant;
import com.coastline.fruit.common.entity.Operator;
import com.coastline.fruit.common.exception.CoastLineFruitException;
import com.coastline.fruit.common.utils.MD5Util;
import com.coastline.fruit.common.utils.SecureRandomUtil;
import com.coastline.fruit.common.utils.ValidateUtils;
import com.coastline.fruit.manage.constants.ManageConstant;
import com.coastline.fruit.manage.exception.ManageErrorInfo;
import com.coastline.fruit.manage.mapper.OperatorMapper;
import com.coastline.fruit.manage.request.CreateOperatorReq;
import com.coastline.fruit.manage.response.CreateOperatorRsp;
import com.coastline.fruit.manage.service.OperatorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.beans.Beans;

/**
 * @author Coastline
 * @date 2025/1/26 21:51
 */
@Slf4j
@Service
public class OperatorServiceImpl implements OperatorService {
    @Resource
    private OperatorMapper operatorMapper;

    /**
     * 新增操作员
     *
     * @param createOperatorReq 新增操作员请求体
     * @return CreateOperatorRsp 新增操作员响求体
     * @throws CoastLineFruitException 异常信息
     */
    @Override
    public CreateOperatorRsp createOperator(CreateOperatorReq createOperatorReq) throws CoastLineFruitException {
        ValidateUtils.checkMandatoryFiled(createOperatorReq.getReqId(), CommonConstant.REQ_ID, ManageErrorInfo.MANDATORY_PARAMS_IS_EMPTY);

        Operator operator = new Operator();
        BeanUtils.copyProperties(createOperatorReq.getOperator(), operator);
        String encryptPassWord = MD5Util.sign(SecureRandomUtil.getPassWord(10), ManageConstant.SALT, ManageConstant.CHARSET);
        operator.setPassword(encryptPassWord);

        CreateOperatorRsp rsp = new CreateOperatorRsp();
        try {
            operatorMapper.createOperator(operator);
            rsp.setResultCode(CommonConstant.SUCCESS_CODE);
            rsp.setResultMessage(CommonConstant.SUCCESS_MSG);
        } catch (Exception e) {
            log.error("createOperator, Database operation error: ", e);
            throw new CoastLineFruitException(ManageErrorInfo.DATABASE_OPERATION_ERROR);
        }
        return rsp;
    }
}
